# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - 量表服务
"""

from datetime import datetime
from app import db
from app.models import Scale, ScalePublisher, User, UserMembership, ScaleQuestion, QuestionOption


class ScaleService:
    """量表服务类"""
    
    @staticmethod
    def check_member_permission(user_id):
        """检查会员权限"""
        user = User.query.get(user_id)
        if not user:
            return False, '用户不存在'
        
        # 临时允许所有用户创建量表进行测试
        # TODO: 在生产环境中恢复会员权限检查
        return True, ''
        
        # 原始会员权限检查代码（已注释）
        # if not user.membership:
        #     return False, '您需要开通会员才能创建量表'
        # 
        # if not user.membership.is_member_active():
        #     return False, '您的会员已过期，请续费'
        # 
        # benefits = user.membership.get_benefits()
        # if not benefits.get('can_create_custom_scales', False):
        #     return False, '您的会员等级不支持创建自定义量表'
        # 
        # return True, ''
    
    @staticmethod
    def check_scale_limit(user_id):
        """检查量表创建数量限制"""
        user = User.query.get(user_id)
        if not user:
            return False, '用户不存在'
        
        # 临时允许所有用户创建量表进行测试（无数量限制）
        # TODO: 在生产环境中恢复数量限制检查
        return True, ''
        
        # 原始数量限制检查代码（已注释）
        # if not user.membership:
        #     return False, '用户不存在或未开通会员'
        # 
        # benefits = user.membership.get_benefits()
        # limit = benefits.get('custom_scale_limit', 0)
        # 
        # # -1 表示无限制
        # if limit == -1:
        #     return True, ''
        # 
        # # 查询当前用户创建的量表数量
        # current_count = db.session.query(ScalePublisher).filter_by(
        #     publisher_type='member',
        #     publisher_id=user_id,
        #     status='active'
        # ).count()
        # 
        # if current_count >= limit:
        #     return False, f'您的会员等级最多只能创建 {limit} 个量表，当前已创建 {current_count} 个'
        # 
        # return True, ''
    
    @staticmethod
    def create_scale(user_id, scale_data):
        """创建量表"""
        try:
            # 检查会员权限
            success, message = ScaleService.check_member_permission(user_id)
            if not success:
                return False, message, None
            
            # 检查数量限制
            success, message = ScaleService.check_scale_limit(user_id)
            if not success:
                return False, message, None
            
            # 验证必需字段
            required_fields = ['title', 'description', 'category_id']
            for field in required_fields:
                if not scale_data.get(field):
                    return False, f'{field} 是必需的', None
            
            user = User.query.get(user_id)
            
            # 创建量表
            scale = Scale(
                title=scale_data['title'],
                subtitle=scale_data.get('subtitle'),
                description=scale_data['description'],
                instruction=scale_data.get('instruction'),
                category_id=scale_data['category_id'],
                status='DRAFT',
                is_public=False,  # 会员创建的量表默认为私有
                is_free=scale_data.get('is_free', True),
                price=scale_data.get('price', 0.0),
                version=scale_data.get('version', '1.0'),
                author=scale_data.get('author', user.username),
                copyright_info=scale_data.get('copyright_info'),
                min_member_level='basic'  # 会员创建的量表默认基础会员可用
            )
            
            db.session.add(scale)
            db.session.flush()
            
            # 创建发布者关系
            publisher = ScalePublisher(
                scale_id=scale.id,
                publisher_type='member',
                publisher_id=user_id,
                status='active'
            )
            
            db.session.add(publisher)
            db.session.commit()
            
            return True, '量表创建成功', scale
            
        except Exception as e:
            db.session.rollback()
            return False, f'创建量表失败: {str(e)}', None
    
    @staticmethod
    def update_scale(user_id, scale_id, scale_data):
        """更新量表"""
        try:
            scale = Scale.query.get(scale_id)
            if not scale:
                return False, '量表不存在', None
            
            # 检查编辑权限
            if not scale.can_edit(user_id):
                return False, '您没有权限编辑此量表', None
            
            # 更新字段
            if 'title' in scale_data:
                scale.title = scale_data['title']
            if 'subtitle' in scale_data:
                scale.subtitle = scale_data['subtitle']
            if 'description' in scale_data:
                scale.description = scale_data['description']
            if 'instruction' in scale_data:
                scale.instruction = scale_data['instruction']
            if 'category_id' in scale_data:
                scale.category_id = scale_data['category_id']
            if 'is_public' in scale_data:
                scale.is_public = scale_data['is_public']
            if 'is_free' in scale_data:
                scale.is_free = scale_data['is_free']
            if 'price' in scale_data:
                scale.price = scale_data['price']
            if 'author' in scale_data:
                scale.author = scale_data['author']
            if 'copyright_info' in scale_data:
                scale.copyright_info = scale_data['copyright_info']
            
            scale.updated_at = datetime.utcnow()
            
            db.session.commit()
            
            return True, '量表更新成功', scale
            
        except Exception as e:
            db.session.rollback()
            return False, f'更新量表失败: {str(e)}', None
    
    @staticmethod
    def delete_scale(user_id, scale_id):
        """删除量表"""
        try:
            scale = Scale.query.get(scale_id)
            if not scale:
                return False, '量表不存在'
            
            # 检查删除权限
            if not scale.can_edit(user_id):
                return False, '您没有权限删除此量表'
            
            # 检查是否有测评记录
            from app.models import Assessment
            assessment_count = Assessment.query.filter_by(scale_id=scale_id).count()
            if assessment_count > 0:
                return False, '该量表已有测评记录，无法删除'
            
            db.session.delete(scale)
            db.session.commit()
            
            return True, '量表删除成功'
            
        except Exception as e:
            db.session.rollback()
            return False, f'删除量表失败: {str(e)}'
    
    @staticmethod
    def add_question(user_id, scale_id, question_data):
        """添加题目"""
        try:
            scale = Scale.query.get(scale_id)
            if not scale:
                return False, '量表不存在', None
            
            # 检查编辑权限
            if not scale.can_edit(user_id):
                return False, '您没有权限编辑此量表', None
            
            # 验证必需字段
            required_fields = ['question_text', 'question_type']
            for field in required_fields:
                if not question_data.get(field):
                    return False, f'{field} 是必需的', None
            
            # 获取下一个题目序号
            max_number = db.session.query(db.func.max(ScaleQuestion.question_number)).filter_by(scale_id=scale_id).scalar() or 0
            question_number = max_number + 1
            
            # 创建题目
            question = ScaleQuestion(
                scale_id=scale_id,
                question_number=question_number,
                question_text=question_data['question_text'],
                question_type=question_data['question_type'],
                is_required=question_data.get('is_required', True)
            )
            
            db.session.add(question)
            db.session.flush()
            
            # 添加选项（如果有）
            options = question_data.get('options', [])
            for i, option_data in enumerate(options):
                option = QuestionOption(
                    question_id=question.id,
                    option_key=option_data.get('option_key', chr(65 + i)),  # A, B, C...
                    option_text=option_data['option_text'],
                    option_value=option_data.get('option_value', i + 1),
                    sort_order=i + 1
                )
                db.session.add(option)
            
            # 更新量表题目数量
            scale.question_count = question_number
            scale.updated_at = datetime.utcnow()
            
            db.session.commit()
            
            return True, '题目添加成功', question
            
        except Exception as e:
            db.session.rollback()
            return False, f'添加题目失败: {str(e)}', None
    
    @staticmethod
    def update_question(user_id, scale_id, question_id, question_data):
        """更新题目"""
        try:
            scale = Scale.query.get(scale_id)
            if not scale:
                return False, '量表不存在', None
            
            # 检查编辑权限
            if not scale.can_edit(user_id):
                return False, '您没有权限编辑此量表', None
            
            question = ScaleQuestion.query.filter_by(id=question_id, scale_id=scale_id).first()
            if not question:
                return False, '题目不存在', None
            
            # 更新题目字段
            if 'question_text' in question_data:
                question.question_text = question_data['question_text']
            if 'question_type' in question_data:
                question.question_type = question_data['question_type']
            if 'is_required' in question_data:
                question.is_required = question_data['is_required']
            
            # 更新选项
            if 'options' in question_data:
                # 删除现有选项
                QuestionOption.query.filter_by(question_id=question_id).delete()
                
                # 添加新选项
                for i, option_data in enumerate(question_data['options']):
                    option = QuestionOption(
                        question_id=question_id,
                        option_key=option_data.get('option_key', chr(65 + i)),
                        option_text=option_data['option_text'],
                        option_value=option_data.get('option_value', i + 1),
                        sort_order=i + 1
                    )
                    db.session.add(option)
            
            question.updated_at = datetime.utcnow()
            scale.updated_at = datetime.utcnow()
            
            db.session.commit()
            
            return True, '题目更新成功', question
            
        except Exception as e:
            db.session.rollback()
            return False, f'更新题目失败: {str(e)}', None
    
    @staticmethod
    def delete_question(user_id, scale_id, question_id):
        """删除题目"""
        try:
            scale = Scale.query.get(scale_id)
            if not scale:
                return False, '量表不存在'
            
            # 检查编辑权限
            if not scale.can_edit(user_id):
                return False, '您没有权限编辑此量表'
            
            question = ScaleQuestion.query.filter_by(id=question_id, scale_id=scale_id).first()
            if not question:
                return False, '题目不存在'
            
            # 删除题目
            db.session.delete(question)
            
            # 重新排序后续题目
            later_questions = ScaleQuestion.query.filter(
                ScaleQuestion.scale_id == scale_id,
                ScaleQuestion.question_number > question.question_number
            ).all()
            
            for q in later_questions:
                q.question_number -= 1
            
            # 更新量表题目数量
            scale.question_count = max(0, scale.question_count - 1)
            scale.updated_at = datetime.utcnow()
            
            db.session.commit()
            
            return True, '题目删除成功'
            
        except Exception as e:
            db.session.rollback()
            return False, f'删除题目失败: {str(e)}'
    
    @staticmethod
    def publish_scale(user_id, scale_id):
        """发布量表"""
        try:
            scale = Scale.query.get(scale_id)
            if not scale:
                return False, '量表不存在'
            
            # 检查编辑权限
            if not scale.can_edit(user_id):
                return False, '您没有权限发布此量表'
            
            # 检查是否可以发布
            if scale.status == 'PUBLISHED':
                return False, '量表已经发布'
            
            # 检查量表完整性
            if scale.question_count == 0:
                return False, '量表必须包含至少一个题目才能发布'
            
            # 检查所有题目是否有选项
            questions = ScaleQuestion.query.filter_by(scale_id=scale_id).all()
            for question in questions:
                if question.question_type in ['single', 'multiple']:
                    option_count = QuestionOption.query.filter_by(question_id=question.id).count()
                    if option_count == 0:
                        return False, f'题目 {question.question_number} 缺少选项'
            
            # 发布量表
            scale.status = 'PUBLISHED'
            scale.published_at = datetime.utcnow()
            scale.updated_at = datetime.utcnow()
            
            db.session.commit()
            
            return True, '量表发布成功'
            
        except Exception as e:
            db.session.rollback()
            return False, f'发布量表失败: {str(e)}'
    
    @staticmethod
    def get_user_scale_stats(user_id):
        """获取用户量表统计信息"""
        try:
            user = User.query.get(user_id)
            if not user:
                return None
            
            # 获取用户创建的量表数量
            created_count = db.session.query(ScalePublisher).filter_by(
                publisher_type='member',
                publisher_id=user_id,
                status='active'
            ).count()
            
            # 获取已发布的量表数量
            published_count = db.session.query(Scale).join(ScalePublisher).filter(
                ScalePublisher.publisher_type == 'member',
                ScalePublisher.publisher_id == user_id,
                ScalePublisher.status == 'active',
                Scale.status == 'PUBLISHED'
            ).count()
            
            # 获取草稿数量
            draft_count = db.session.query(Scale).join(ScalePublisher).filter(
                ScalePublisher.publisher_type == 'member',
                ScalePublisher.publisher_id == user_id,
                ScalePublisher.status == 'active',
                Scale.status == 'DRAFT'
            ).count()
            
            # 获取会员限制
            benefits = user.membership.get_benefits() if user.membership else {}
            limit = benefits.get('custom_scale_limit', 0)
            
            stats = {
                'created_count': created_count,
                'published_count': published_count,
                'draft_count': draft_count,
                'scale_limit': limit,
                'can_create_more': limit == -1 or created_count < limit,
                'remaining_quota': max(0, limit - created_count) if limit > 0 else -1
            }
            
            return stats
            
        except Exception as e:
            return None